﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CommonLib;
using log4net;
using HtmlAgilityPack;

using GmailFetcher.Models;

namespace GmailFetcher.Processors
{

    public class CouponProcessor : ProcessInterface
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public bool processrawData(object rawDatatoProcess, string configPath)
        {
            log.DebugFormat(" Coupon Processor Kicked Off  :  Processing Data Happily:-) ");
            var crawledData = rawDatatoProcess as EmailCrawledData;

            if (crawledData == null)
            {
                return false;
            }


            foreach( var emailMsg  in crawledData._emailList)
            {
                log.DebugFormat("Message : {0} ", emailMsg.Text);
                ProcessHtml(emailMsg.Text);
            }
            
            return true;
        }

        private bool ProcessHtml(string htmlText)
        {
            var htmlDocument = new HtmlDocument();

            // remove the Junk Before HTML Doc 
            const string delim = "<html>";
            string htmlDoc = htmlText;
            if (htmlText.IndexOf(value: delim, comparisonType: System.StringComparison.Ordinal) > 0)
            {
                htmlDoc = htmlDoc.Remove(0, htmlDoc.IndexOf(delim, System.StringComparison.Ordinal));
            }

            // Construct the document
            htmlDocument.LoadHtml(htmlDoc);
            
            return true;
        }


    }
}
